package com.example.demo.utils;


import java.io.IOException;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class HttpUtil {
	
	private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class);
	private static OkHttpClient client = null;
	
	public static JSONObject doGet(String url){
		client = getClient();
		try {
			logger.info("请求地址是"+url);
			Request request = new Request.Builder().url(url)
					          .get()
					          .build();
			Response response = client.newCall(request).execute();
			if(response.isSuccessful()) {
			   ResponseBody responseBody = response.body();
			   if(null != responseBody) {
				   JSONObject json = JSONObject.parseObject(responseBody.string());
				   return json;
			   }
				
			}
		} catch (IOException e) {
			logger.error("错误信息是"+e.getMessage());
		}
		
		return null;
	}
	
	public static void sendMessage(String message,String url) {
		 try {
			 logger.info("请求开始");
			 MediaType mediatype = MediaType.parse("application/json; charset=utf-8");
			 RequestBody requestBody = RequestBody.create(mediatype, message);
			 Request request = new Request.Builder().url(url)
			         .post(requestBody)
			         .build();
			 Response response = getClient().newCall(request).execute();
			 if(response.isSuccessful()) {
				   ResponseBody responseBody = response.body();
				   if(null != responseBody) {
					   JSONObject json = JSONObject.parseObject(responseBody.string());
					   System.out.println(json.toJSONString());
				   }
					
				}
		} catch (IOException e) {
			logger.error("请求失败，失败信息为"+e.getMessage());
		}
	}
	
	public static OkHttpClient getClient() {
		if(null == client) {
			client = new OkHttpClient.Builder()
					     .connectTimeout(10, TimeUnit.SECONDS)
					     .readTimeout(20, TimeUnit.SECONDS)
					     .build();
		}
		return client;
	}
	

}
